package com.utcs.modules.resource.basic.controller;

import com.utcs.common.utils.StringUtils;
import com.utcs.modules.resource.basic.security.FormAuthenticationFilter;
import com.utcs.modules.resource.basic.security.SystemAuthorizingRealm.Principal;
import com.utcs.modules.resource.basic.utils.UserUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Fly on 2017/5/23.
 */
@Controller
public class LoginController {

    Logger logger = Logger.getLogger(this.getClass());



    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(HttpServletRequest request, HttpServletResponse response){
        logger.info("login get");
        Principal principal = UserUtils.getPrincipal();

        // 如果已经登录，则跳转到管理首页
        if(principal != null && !principal.isMobileLogin()){
            return "redirect:" + "/";
        }
        return "login";
    }

    /**
     * 登录失败，真正登录的POST请求由Filter完成
     * @param request
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String loginFailure(HttpServletRequest request, Model model){
        Principal principal = UserUtils.getPrincipal();

        // 如果已经登录，则跳转到管理首页
        if(principal != null && !principal.isMobileLogin()){
            return "redirect:" + "/";
        }

        String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        String message = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

        if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
            message = "用户或密码错误, 请重试.";
        }
        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);

        return "login";
    }

    /**
     * 登陆成功 进入管理页面
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "/")
    public String index(){
        logger.info("login success");
        return "main";
    }
}
